﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FileDB;
namespace Rem.Objects.Forms
{
    public partial class ContractForm : BaseForm
    {
        Contract contract { get { return base.Data as Contract; } }
        public ContractForm()
            : this("新建合同")
        {

        }
        public const string TextTemplate = "合同#{0}-{1}";
        public ContractForm(Contract contract)
        {
            InitializeComponent();
            this.paymentTypeCmbox.Items.Clear();
            this.paymentTypeCmbox.Items.Add(Contract.RentUnit_Month);
            this.paymentTypeCmbox.Items.Add(Contract.RentUnit_Year);
            this.Data = contract;
            DisplayInfo();
        }

        private void DisplayInfo()
        {
            this.addressTextBox.Text = contract.Address;
            this.contractNoTextBox.Text = contract.ContractNo;
            this.areaSizeNumericUpDown.Value = (decimal)(contract.AreaSize);
            this.widthNumericUpDown.Value = (decimal)(contract.Width);

            this.rentNumericUpDown.Value = (decimal)contract.RentPerInterval;
            this.rentIntervalNumericUpDown.Value = contract.RentInterval;
            this.depositNumericUpDown.Value = (decimal)contract.Deposit;
            this.advancedDaysNumericUpDown.Value = contract.AdvancedDays;


            this.freeDaysInNumericUpDown.Value = contract.FreeDaysIn;
            this.freeDaysOutNumericUpDown.Value = contract.FreeDaysOut;

            this.startDateDateTimePicker.Value = contract.StartDate;
            this.dueDateDateTimePicker.Value = contract.DueDate;
            this.nudRenew.Value = (decimal)contract.AdvancedRenew;
            this.signTimeDateTimePicker.Value = contract.SignTime;

            this.commentTextBox.Text = contract.Comment;
            this.paymentTypeCmbox.Text = contract.RentUnit;
            this.upNumTax.Value = contract.TaxRate;
            this.chbCanTicket.Checked = contract.CanTicket;
            UpdateTax();
            if (contract.Id > 0)
            {
                this.label1RentInThisPeriod.Text = string.Format("应{0}租金:{1}元",
                    Customer.GetSelfCompany().Id == contract.PartAId ? "收" : "缴",
                    contract.GetRentInThisYearForSignalContract().ToString("###,###,##0"));
            }
            else
            {
                this.label1RentInThisPeriod.Text = "暂无信息";
            }
            if (this.contract != null)
            {
                if (this.contract.CustomerPartA != null && this.contract.PartAId > 0)
                {
                    this.partANameLinkLabel.Text = this.contract.CustomerPartA.Name;
                    this.partANameLinkLabel.Tag = this.contract.CustomerPartA;
                }
                if (this.contract.CustomerPartB != null && this.contract.PartBId > 0)
                {
                    this.partBNameLinkLabel.Text = this.contract.CustomerPartB.Name;
                    this.partBNameLinkLabel.Tag = this.contract.CustomerPartB;
                }

            }

            UpdateRentType();
            lblID.Text = string.Format(QueryConstants.IDTemplate, contract.Id.ToString());

            this.toolStripButton1.Text = this.contract.Status == null || this.contract.Status.Contains(ReminderState.Disable) ? ReminderState.Actived : ReminderState.Disable;
            this.Text = string.Format(TextTemplate, contract.ContractNo, contract.Address);
        }

        public ContractForm(string text)
            : this(new Contract())
        {
            this.Text = text;
            //this.ucContract2.Saved += new EventHandler(Saved);
        }



        public void Saved(object sender, EventArgs e)
        {
            Contract contract = sender as Contract;
            this.Text = string.Format(TextTemplate, contract.Id, contract.Address);
        }

        public override BaseObjectTypes BaseType
        {
            get
            {
                return BaseObjectTypes.Contract;
            }
        }

        private void deleteToolStripButton_Click(object sender, EventArgs e)
        {
            if (this.contract.Id <= 0)
            {
                return;
            }
            DialogResult result = MessageBox.Show("确定删除此合同！", "合同删除", MessageBoxButtons.YesNo);
            if (result != DialogResult.Yes)
            {
                return;
            }
            try
            {
                this.Cursor = Cursors.WaitCursor;
                try
                {
                    Contract.Delete(this.contract);
                    if (base.Deleted != null)
                    {
                        base.Deleted(this, null);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除出错或数据不存在！", "合同删除", MessageBoxButtons.OK);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
            this.Close();
        }
        public void AfterSaved(object sender, EventArgs e)
        {
            Contract employee = sender as Contract;
            this.Text = string.Format(TextTemplate, employee.Id, employee.Address);
        }
        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.Arrow;
                if (GetContract())
                {
                    Contract.Save(this.contract);
                    base.Save();
                    DisplayInfo();

                    MessageBox.Show("保存成功", "保存提示", MessageBoxButtons.OK);
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private bool GetContract()
        {
            #region
            if (string.IsNullOrWhiteSpace(this.addressTextBox.Text))
            {
                MessageBox.Show("请填写地址信息！");
                return false;
            }

            if (string.IsNullOrWhiteSpace(this.contractNoTextBox.Text))
            {
                MessageBox.Show("请填写合同编号！");
                return false;
            }

            if (this.dueDateDateTimePicker.Value <= this.startDateDateTimePicker.Value)
            {
                MessageBox.Show("结束日期没有大于开始日期！");
                return false;
            }
            Customer partA = this.partANameLinkLabel.Tag as Customer;
            if (partA == null || partA.Id <= 0)
            {
                if (string.IsNullOrWhiteSpace(this.partANameLinkLabel.Text))
                {
                    MessageBox.Show("请填写收租方客户信息！");
                    return false;
                }
                partA = new Customer() { Id = QueryConstants.UnsavedObjectId, Name = this.partANameLinkLabel.Text };
                Customer.Insert(partA);
                this.partANameLinkLabel.Tag = partA;
            }
            if (partA != null)
            {
                contract.PartAId = partA.Id;
            }
            Customer partB = this.partBNameLinkLabel.Tag as Customer;
            if (partB == null || partB.Id <= 0)
            {
                if (string.IsNullOrWhiteSpace(this.partBNameLinkLabel.Text))
                {
                    MessageBox.Show("请填写缴租方客户信息！");
                    return false;
                }
                partB = new Customer() { Id = QueryConstants.UnsavedObjectId, Name = this.partBNameLinkLabel.Text };
                Customer.Insert(partB);
                this.partBNameLinkLabel.Tag = partB;
            }
            if (partB != null)
            {
                contract.PartBId = partB.Id;
            }

            if (contract.PartBId == contract.PartAId)
            {
                MessageBox.Show("收租方和缴租方为同一客户，请更改！");
                return false;
            }

            var customer = Customer.GetSelfCompany();
            if (customer == null || customer.Id < 1)
            {
                MessageBox.Show("请设置一客户为本公司！");
                return false;
            }

            if (customer.Id != contract.PartBId && customer.Id != contract.PartAId)
            {
                MessageBox.Show("收租或缴租方至少一方为本公司！");
                return false;
            }
            #endregion

            #region assgin data
            this.contract.SignTime = this.signTimeDateTimePicker.Value;

            this.contract.Address = this.addressTextBox.Text;
            this.contract.ContractNo = this.contractNoTextBox.Text;
            this.contract.AreaSize = this.areaSizeNumericUpDown.Value;
            this.contract.Width = this.widthNumericUpDown.Value;


            this.contract.Deposit = (double)(this.depositNumericUpDown.Value);
            //每月租金
            this.contract.RentInterval = (int)this.rentIntervalNumericUpDown.Value;
            //this.contract.SubmitRentDate = (int)this.submitRentDateComboBox.SelectedValue;

            this.contract.RentPerInterval = (double)this.rentNumericUpDown.Value;
            this.contract.AdvancedDays = (int)this.advancedDaysNumericUpDown.Value;

            this.contract.AdvancedRenew = (int)this.nudRenew.Value;
            this.contract.StartDate = this.startDateDateTimePicker.Value;
            this.contract.DueDate = this.dueDateDateTimePicker.Value;
            this.contract.RentUnit = this.paymentTypeCmbox.Text;
            this.contract.FreeDaysIn = (int)this.freeDaysInNumericUpDown.Value;
            this.contract.FreeDaysOut = (int)this.freeDaysOutNumericUpDown.Value;
            this.contract.Comment = this.commentTextBox.Text;
            this.contract.TaxRate = this.upNumTax.Value;
            this.contract.CanTicket = this.chbCanTicket.Checked;
            #endregion
            return true;
        }

        private void newToolStripButton_Click(object sender, EventArgs e)
        {
            if (this.contract.Id > 0)
            {
                (new ContractForm() { Dock = DockStyle.Fill }).Show();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        private void reminderPeriodBuildbtn_Click(object sender, EventArgs e)
        {
            if (contract.Id < 1)
            {
                return;
            }

            if (MessageBox.Show("更新提醒将删除此合同所有提醒,并根据合同当前数据重新生成提醒！确认更新提醒？", "更新提醒", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            try
            {
                Cursor.Current = Cursors.Arrow;
                foreach (var r in Reminder.GetReminder(this.contract.Id))
                {
                    r.Delete();
                }
                Contract.GenerateRinders(this.contract);
                UcDataGrid.InitializateGridView(this.reminderDataGridView, Reminder.GetReminder(contract.Id),
                QueryConstants.ReminderFieldNameHeadTextMapping, QueryConstants.ReminderInvisiableFieldNames);
            }
            catch (Exception ex)
            {
                Logger.WriteError(BaseObjectTypes.Contract, this.contract, ex);
                MessageBox.Show("更新提醒失败！", "更新提醒", MessageBoxButtons.OK);

            }
            finally
            {
                Cursor.Current = Cursors.Default;
                MessageBox.Show("更新提醒成功！", "更新提醒", MessageBoxButtons.OK);
            }

            //ReminderForm2 form = new ReminderForm2(new Reminder()
            //{
            //    ContractId = contract.Id,
            //    ReminderTime = contract.StartDate.AddDays(-contract.AdvancedDays),
            //    StartTime = contract.StartDate,
            //    DueTime = contract.DueDate
            //}) { Text = string.Format("生成提醒#合同{0}", contract.ContractNo) };

            //form.Dock = DockStyle.Fill;
            //form.periedgroupBox.Visible = true;

            //form.GenerateReminders += (source, arg) =>
            //{
            //    IEnumerable<Reminder> reminders = source as IEnumerable<Reminder>;
            //    if (reminders != null)
            //    {
            //        QueryForm.OpenReminderQuery(0, "合同周期提醒", reminders);
            //    }
            //    this.Focus();
            //    form.saveToolStripButton.Enabled = false;
            //};
            //form.Show();
        }

        private void deleteReminder(object sender, EventArgs e)
        {
            if (contract.Id < 1)
            {
                return;
            }

            if (MessageBox.Show("确定删除吗？", "数据删除", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
            {
                return;
            }
            try
            {
                Cursor.Current = Cursors.Arrow;
                foreach (DataGridViewRow row in reminderDataGridView.SelectedRows)
                {
                    Reminder info = row.DataBoundItem as Reminder;
                    if (!info.Delete())
                    {
                        MessageBox.Show("提醒删除失败！", "提醒删除", MessageBoxButtons.OK);
                        break;
                    }
                }
                UcDataGrid.InitializateGridView(this.reminderDataGridView, Reminder.GetReminder(contract.Id),
                QueryConstants.ReminderFieldNameHeadTextMapping, QueryConstants.ReminderInvisiableFieldNames);
            }
            catch (Exception ex)
            {
                Logger.WriteError(BaseObjectTypes.Contract, this.contract, ex);
                MessageBox.Show("提醒删除失败", "提醒删除", MessageBoxButtons.OK);
            }

            finally
            {
                MessageBox.Show("提醒删除成功", "提醒删除", MessageBoxButtons.OK);
                Cursor.Current = Cursors.Default;

            }

        }

        private void addReminders(object sender, EventArgs e)
        {
            if (contract.Id > 0)
            {
                ReminderForm2 form = new ReminderForm2(new Reminder() { ContractId = contract.Id }) { Text = string.Format("生成提醒#合同{0}", contract.ContractNo) };
                form.periedgroupBox.Visible = false;

                form.GenerateReminders += (source, arg) =>
                {
                    //auto upodate
                    //IEnumerable<Reminder> reminders = source as IEnumerable<Reminder>;
                    //if (reminders != null && reminders.Count() == 1)
                    //{
                    //    this.contract.Reminders.Add(reminders.Single());
                    //}
                    //this.Focus();
                    //form.saveToolStripButton.Enabled = false;
                    //form.Close();
                };
                form.Show();
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (contract.Id > 0)
            {

            }
        }

        private void reminderSettingTabPage_Enter(object sender, EventArgs e)
        {
            if (this.contract.Id > 0)
            {
                UcDataGrid.InitializateGridView(this.reminderDataGridView, Reminder.GetReminder(contract.Id),
                    QueryConstants.ReminderFieldNameHeadTextMapping, QueryConstants.ReminderInvisiableFieldNames);
                this.reminderDataGridView.Refresh();
            }
        }
        private void selectCustormerBtn_Click(object sender, EventArgs e)
        {
            SelectCustomer(partANameLinkLabel);
        }

        private void button11_Click(object sender, EventArgs e)
        {
            SelectCustomer(partBNameLinkLabel);
        }

        private void SelectCustomer(LinkLabel customerLabel)
        {
            ObjectPickerForm picker = new ObjectPickerForm(BaseObjectTypes.Customer);
            picker.ShowDialog();
            if (picker.DialogResult == DialogResult.OK)
            {
                Customer customer = picker.SelectedObject as Customer;
                if (customer != null)
                {
                    customerLabel.Text = customer.Name;
                    customerLabel.Tag = customer;
                    UpdateRentType();
                }
            }
        }

        private void UpdateRentType()
        {

            if (partANameLinkLabel.Tag is Customer)
            {
                if (Customer.GetSelfCompany().Id == (partANameLinkLabel.Tag as Customer).Id)
                {
                    rentTypeLable.Text = "收租";

                }
                else
                {
                    rentTypeLable.Text = "缴租";
                }
            }
            else
            {
                rentTypeLable.Text = "暂无";
            }
        }

        private void partANameLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Customer customer = (sender as LinkLabel).Tag as Customer;
            if (customer != null && customer.Id > 0)
            {
                CustomerForm form = new CustomerForm(customer) { Dock = DockStyle.Fill };
                form.Show();
                form.FormClosing += (object f, FormClosingEventArgs arg) =>
                    {
                        if (f as CustomerForm != null)
                        {
                            CustomerForm fm = f as CustomerForm;
                            if (fm.Customer != null && fm.Customer.Id > 0)
                            {
                                (sender as LinkLabel).Text = fm.Customer.Name;
                            }
                        }
                    };
            }
            else
            {
                CustomerForm form = new CustomerForm();
                form.Show();
                form.FormClosing += (object f, FormClosingEventArgs arg) =>
                {
                    if (f as CustomerForm != null)
                    {
                        CustomerForm fm = f as CustomerForm;
                        if (fm.Customer != null && fm.Customer.Id > 0)
                        {
                            (sender as LinkLabel).Text = fm.Customer.Name;
                        }
                    }
                };
            }
        }

        private void partBNameLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            partANameLinkLabel_LinkClicked(sender, e);
        }

        private void openToolStripButton_Click(object sender, EventArgs e)
        {
            var ids = GoToForm.GetID("Id", "Address", BaseObjectTypes.Contract);

            if (ids.Count == 1)
            {
                int objectId = ids.Count == 1 ? ids[0] : QueryConstants.UnsavedObjectId;
                Contract contract = Contract.GetContract(objectId);
                if (contract != null && contract.Id > 0)
                {
                    ContractForm f = new ContractForm(contract);
                    f.Show();
                    f.Dock = DockStyle.Fill;
                }
            }
            else
            {
                var datasource = (from id in ids

                                  select Contract.GetContract(id)).ToList();
                QueryForm f = new QueryForm(BaseObjectTypes.ContractQuery, "合同查询", datasource);
                f.Dock = DockStyle.Fill;
                f.Show();

            }
        }

        private void contractAddtionalInfoesDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void removeAdditionalInfo(object sender, EventArgs e)
        {
            if (this.contract == null || this.contract.Id < 1)
                return;
            if (this.contractAddtionalInfoesDataGridView.SelectedRows.Count == 1)
            {
                AdditionInfo info = contractAddtionalInfoesDataGridView.SelectedRows[0].DataBoundItem as AdditionInfo;
                if (AdditionInfo.DeleteAdditionalInfo(this.contract.Id, info))
                {
                    UcDataGrid.InitializateGridView(
                    contractAddtionalInfoesDataGridView,
                    AdditionInfo.GetAdditionalInfo(this.contract.Id),
                     QueryConstants.ContractAdditionalInfoFieldNameHeadTextMapping,
                     QueryConstants.ContractAdditionalInfoInvisiableFieldNames);

                    //this.contractAddtionalInfoesDataGridView.Rows.RemoveAt(contractAddtionalInfoesDataGridView.SelectedRows[0].Index);
                    this.contractAddtionalInfoesDataGridView.Refresh();
                    DisplayCalcalate(contractAddtionalInfoesDataGridView);
                }
                else
                {
                    MessageBox.Show("删除数据失败！", "数据删除", MessageBoxButtons.OK);
                }
            }

        }

        private void AddAdditionalInfo(object sender, EventArgs e)
        {
            if (this.contract == null && this.contract.Id < 1)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(this.addtionalContentTextBox.Text))
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(this.addtionalValueTextBox.Text))
            {
                return;
            }

            AdditionInfo info = new AdditionInfo()
            {
                Id = QueryConstants.UnsavedObjectId,
                Key = this.addtionalContentTextBox.Text,
                Value = this.addtionalValueTextBox.Text
            };

            try
            {
                Cursor.Current = Cursors.Arrow;
                AdditionInfo.SaveAdditionalInfo(this.contract.Id, info);
                UcDataGrid.InitializateGridView(
                    contractAddtionalInfoesDataGridView,
                    AdditionInfo.GetAdditionalInfo(this.contract.Id),
                     QueryConstants.ContractAdditionalInfoFieldNameHeadTextMapping,
                     QueryConstants.ContractAdditionalInfoInvisiableFieldNames);
                this.contractAddtionalInfoesDataGridView.Refresh();
                DisplayCalcalate(contractAddtionalInfoesDataGridView);
            }
            catch (Exception ex)
            {
                Logger.WriteError(BaseObjectTypes.AdditionalInfo, info, ex);
                MessageBox.Show("保存数据出错", "保存", MessageBoxButtons.OK);
            }

            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void DisplayCalcalate(DataGridView datagridview)
        {
            var infos = datagridview.DataSource as List<AdditionInfo>;
            double total = 0;
            foreach (var info in infos)
            {
                double value;
                double.TryParse(info.Value, out value);
                total += value;
            }
            if (infos != null && infos.Count > 0)
                this.label15.Text = string.Format("金额累计:{0}元", total.ToString("###,###,##0"));
            else
                this.label15.Text = string.Empty;
        }

        private void updateAdditionInfo(object sender, EventArgs e)
        {
            if (this.contract == null && this.contract.Id < 1)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(this.addtionalContentTextBox.Text))
            {
                return;
            }

            if (this.contractAddtionalInfoesDataGridView.SelectedRows.Count == 1)
            {
                AdditionInfo info = contractAddtionalInfoesDataGridView.SelectedRows[0].DataBoundItem as AdditionInfo;
                info.Key = this.addtionalContentTextBox.Text;
                info.Value = this.addtionalValueTextBox.Text;
                if (AdditionInfo.UpdateAdditionalInfo(this.contract.Id, info))
                {
                    UcDataGrid.InitializateGridView(
                    contractAddtionalInfoesDataGridView,
                    AdditionInfo.GetAdditionalInfo(this.contract.Id),
                     QueryConstants.ContractAdditionalInfoFieldNameHeadTextMapping,
                     QueryConstants.ContractAdditionalInfoInvisiableFieldNames);
                    DisplayCalcalate(contractAddtionalInfoesDataGridView);
                }
                else
                {
                    MessageBox.Show("删除数据失败！", "数据删除", MessageBoxButtons.OK);
                }
            }
        }

        private void tabPage1_Enter(object sender, EventArgs e)
        {
            if (this.contract != null && this.contract.Id > 0)
            {
                if (this.additionalInfoPage.Tag == null)
                {
                    UcDataGrid.InitializateGridView(
                    contractAddtionalInfoesDataGridView,
                    AdditionInfo.GetAdditionalInfo(this.contract.Id),
                     QueryConstants.ContractAdditionalInfoFieldNameHeadTextMapping,
                     QueryConstants.ContractAdditionalInfoInvisiableFieldNames);
                    DisplayCalcalate(contractAddtionalInfoesDataGridView);
                    this.additionalInfoPage.Tag = new object();
                }
            }
        }

        private void contractAddtionalInfoesDataGridView_RowEnter_1(object sender, DataGridViewCellEventArgs e)
        {
            if (contractAddtionalInfoesDataGridView.SelectedRows.Count == 1)
            {
                AdditionInfo info = contractAddtionalInfoesDataGridView.SelectedRows[0].DataBoundItem as AdditionInfo;
                if (info != null && info.Id > 0)
                {
                    this.addtionalContentTextBox.Text = info.Key;
                    this.addtionalValueTextBox.Text = info.Value;
                }
            }
        }

        private void upNumTax_ValueChanged(object sender, EventArgs e)
        {
            UpdateTax();
        }

        private void UpdateTax()
        {
            if (this.contract != null && this.contract.Id > 0)
            {
                labelTax.Text = string.Format("{0} 元", this.contract.RentInInterval * (double)this.upNumTax.Value / 100);
            }
            else
            {
                labelTax.Text = string.Format("{0} 元", 0.0);
            }
        }

        private void reminderDataGridView_DoubleClick(object sender, EventArgs e)
        {

            if (contract.Id < 1)
                return;
            foreach (DataGridViewRow row in reminderDataGridView.SelectedRows)
            {
                Reminder info = row.DataBoundItem as Reminder;
                FormHelper.OpenObjectForm(BaseObjectTypes.ReminderQuery, info);
            }
        }



    }
}
